import './Scss/TestData.scss'
import './TestTemp.scss'
import { Column } from '@ant-design/plots'
import { useState, useRef, useEffect } from 'react'
import { useRequest, useSize, useBoolean, useEventEmitter } from 'ahooks'
import { Select } from 'antd'
import { Http } from '../../../../Common/Api'
import { CaretDownOutlined } from '@ant-design/icons'
import { TestNameMapping, TestTypeMapping } from '../../../../Common/Configure/CommonParameter'
import { TitleSmall001 } from '../Common/SmallTitle'
import { FrontModalBox } from '../Modal'

import { WebCommonUrl } from '../../../../Common/Configure/CommonParameter'

import { ColumnStyle, ColumnConfigA01Template, PieTemplate } from './AssetsCharts'

export const TestData001 = ({ LabList, title, opgType }) => {
    const BoxCharts = useRef()
    const size = useSize(BoxCharts)
    const [ActiveOne, setActiveOne] = useState()
    const [ActiveTwo, setActiveTwo] = useState()
    const [TabsOne, setTabsOne] = useState([])
    const [TabsTwo, setTabsTwo] = useState([])
    const [OneData, setOneData] = useState([])
    const [TwoData, setTwoData] = useState([])
    const { runAsync: getOrganizationsA } = useRequest(Http, { manual: true })
    const { runAsync: getOrganizationsB } = useRequest(Http, { manual: true })
    const { runAsync: getConstructionLabDataStatA } = useRequest(Http, { manual: true })
    const { runAsync: getConstructionLabDataStatB } = useRequest(Http, { manual: true })

    useEffect(() => {
        console.log(opgType)
        if (opgType?.A) {
            getOrganizationsA({ url: 'getOrganizations', data: { OrgType: opgType.A } }).then(({ list }) => {
                let data = list.map(({ uuid, tableName }) => ({ label: tableName, value: uuid }))
                data = [{ label: '全部', value: opgType.A }, ...data]
                setActiveOne(opgType.A)
                setTabsOne(data)
            })
        }
    }, [getOrganizationsA, opgType])

    useEffect(() => {
        if (opgType?.B) {
            getOrganizationsB({ url: 'getOrganizations', data: { OrgType: opgType.B } }).then(({ list }) => {
                let data = list.map(({ uuid, tableName }) => ({ label: tableName, value: uuid }))
                data = [{ label: '全部', value: opgType.B }, ...data]
                setActiveTwo(opgType.B)
                setTabsTwo(data)
            })
        }
    }, [getOrganizationsB, opgType])

    const [ChartsOne, setChartsOne] = useState()
    const [ChartsTwo, setChartsTwo] = useState()

    useEffect(() => {
        if (size) {
            const { width, height } = size
            const configOne = {
                data: OneData,
                color: 'l(90) 0:rgba(176, 254, 246, 1) 1:rgba(176, 254, 246, 0.4)',
                autoFit: false,
                width,
                height,
                maxColumnWidth: 14,
                appendPadding: 16,
                xField: 'type',
                yField: '试验次数',
                xAxis: {
                    label: { style: { fill: '#B2FBFD' } },
                    line: { style: { stroke: '#B2FBFD' } },
                    tickLine: { style: { stroke: '#B2FBFD' } },
                },
                yAxis: {
                    title: { text: '组', position: 'end', autoRotate: false, offset: 55, style: { fill: '#B2FBFD' } },
                    tickCount: 5,
                    label: { style: { fill: '#B2FBFD' }, formatter: e => e },
                    grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
                },
                scrollbar: {
                    type: 'horizontal',
                    height: 8,
                    categorySize: 80,
                    style: {
                        trackColor: 'rgba(178, 251, 253, 0.2)',
                        thumbColor: 'rgba(178, 251, 253, 0.6)',
                        thumbHighlightColor: '#B2FBFD',
                    },
                },
            }
            setChartsOne(configOne)
        }
    }, [OneData, size])

    useEffect(() => {
        if (size) {
            const { width, height } = size
            const configTwo = {
                data: TwoData,
                color: 'l(90) 0:rgba(255, 218, 138, 1) 1:rgba(255, 218, 138, 0.4)',
                autoFit: false,
                width,
                height,
                maxColumnWidth: 14,
                appendPadding: 16,
                xField: 'type',
                yField: '试验次数',
                xAxis: {
                    label: { style: { fill: '#B2FBFD' } },
                    line: { style: { stroke: '#B2FBFD' } },
                    tickLine: { style: { stroke: '#B2FBFD' } },
                },
                yAxis: {
                    title: { text: '组', position: 'end', autoRotate: false, offset: 55, style: { fill: '#B2FBFD' } },
                    tickCount: 5,
                    label: { style: { fill: '#B2FBFD' }, formatter: e => e },
                    grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
                },
                scrollbar: {
                    type: 'horizontal',
                    height: 8,
                    categorySize: 80,
                    style: {
                        trackColor: 'rgba(178, 251, 253, 0.2)',
                        thumbColor: 'rgba(178, 251, 253, 0.6)',
                        thumbHighlightColor: '#B2FBFD',
                    },
                },
            }
            setChartsTwo(configTwo)
        }
    }, [TwoData, size])

    useEffect(() => {
        if (ActiveOne)
            getConstructionLabDataStatA({
                url: 'getConstructionGetlabDataStatByOrg',
                data: {
                    OrganizationUuid: ActiveOne,
                    LabType: LabList,
                },
            }).then(res =>
                setOneData(
                    Object.keys(res).map(item => ({
                        type: TestNameMapping[item].title,
                        试验次数: res[item],
                        uuid: TestNameMapping[item].uuid,
                        OrganizationUuid: ActiveOne,
                    })),
                ),
            )
    }, [ActiveOne, getConstructionLabDataStatA, LabList])

    useEffect(() => {
        if (ActiveTwo)
            getConstructionLabDataStatB({
                url: 'getConstructionGetlabDataStatByOrg',
                data: {
                    OrganizationUuid: ActiveTwo,
                    LabType: LabList,
                },
            }).then(res =>
                setTwoData(
                    Object.keys(res).map(item => ({
                        type: TestNameMapping[item].title,
                        试验次数: res[item],
                        uuid: TestNameMapping[item].uuid,
                        OrganizationUuid: ActiveTwo,
                    })),
                ),
            )
    }, [ActiveTwo, getConstructionLabDataStatB, LabList])

    const [OptionsCall, setOptionsCall] = useState()
    const OptionsEvent = useEventEmitter()
    OptionsEvent.useSubscription(val => setOptionsCall(val))

    const ClickCharts = (plot, e, type) => {
        const { x, y } = e
        const [{ data }] = plot.chart.getTooltipItems({ x, y })
        const { uuid, OrganizationUuid } = data
        const { label, title } = TestTypeMapping[uuid]

        setOptionsCall({
            type: 'TableList',
            data: {
                title,
                type: label,
                uuid: OrganizationUuid,
                list: type === 1 ? 'lab_self' : 'lab_sampling',
            },
        })
    }
    return (
        <div className="TestData001">
            <div>
                <TitleSmall001 title={title ? title[0] : 'Z+B试验数据'} />
                <div className="Tabs">
                    <Select
                        value={ActiveTwo}
                        style={{ width: '100%' }}
                        options={TabsTwo}
                        suffixIcon={<CaretDownOutlined style={{ color: 'white' }} />}
                        onChange={e => setActiveTwo(e)}
                    />
                </div>
                <div className="Charts">
                    {ChartsTwo && (
                        <Column {...ChartsTwo} onReady={plot => plot.on('plot:click', e => ClickCharts(plot, e, 2))} />
                    )}
                </div>
            </div>
            <div>
                <TitleSmall001 title={title ? title[1] : 'A试验数据'} />
                <div className="Tabs">
                    <Select
                        value={ActiveOne}
                        style={{ width: '100%' }}
                        options={TabsOne}
                        suffixIcon={<CaretDownOutlined style={{ color: 'white' }} />}
                        onChange={e => setActiveOne(e)}
                    />
                </div>
                <div className="Charts" ref={BoxCharts}>
                    {ChartsOne && (
                        <Column {...ChartsOne} onReady={plot => plot.on('plot:click', e => ClickCharts(plot, e, 1))} />
                    )}
                </div>
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const TestData002 = ({ LabType }) => {
    const ChartsBox = useRef()
    const size = useSize(ChartsBox)
    const { runAsync: getConstructionLabDataStatA } = useRequest(Http, { manual: true })
    const [Data, setData] = useState([])
    const [ChartData, setChartData] = useState()

    useEffect(() => {
        getConstructionLabDataStatA({
            url: 'getConstructionGetlabDataStatByOrg',
            data: { LabType },
        }).then(res =>
            setData(
                Object.keys(res).map(item => ({
                    type: TestNameMapping[item].title,
                    试验次数: res[item],
                    uuid: TestNameMapping[item].uuid,
                    OrganizationUuid: '64ed4d71-117b-4a27-a6b9-8b7285993284',
                })),
            ),
        )
    }, [LabType, getConstructionLabDataStatA])

    useEffect(() => {
        if (size) {
            const { width, height } = size
            const config = {
                data: Data,
                autoFit: false,
                width,
                height: height,
                appendPadding: 16,
                maxColumnWidth: 14,
                xField: 'type',
                yField: '试验次数',
                color: '#24C4FF',
                xAxis: {
                    label: { style: { fill: 'white' } },
                    line: { style: { stroke: '#3BACE9' } },
                    tickLine: { style: { stroke: '#3BACE9' } },
                },
                yAxis: {
                    title: { text: '组', position: 'end', autoRotate: false, offset: 50, style: { fill: 'white' } },
                    tickCount: 5,
                    label: { style: { fill: '#3BACE9' } },
                    grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
                },
            }
            setChartData(config)
        }
    }, [Data, size])
    const [TowModal, { setTrue, setFalse }] = useBoolean(false)
    const [ParameterTitle, setParameterTitle] = useState()
    const [Parameter, setParameter] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const ExperimentalThrEvent = useEventEmitter()
    ExperimentalThrEvent.useSubscription(res => setOptionsCall(res))

    return (
        <div className="TestData002" ref={ChartsBox}>
            {ChartData && (
                <Column
                    {...ChartData}
                    onReady={plot =>
                        plot.on('plot:click', e => {
                            const { x, y } = e
                            const [{ data }] = plot.chart.getTooltipItems({ x, y })
                            const { uuid } = data
                            const { label, title } = TestTypeMapping[uuid]
                            setOptionsCall({
                                type: 'TableList',
                                data: { title, type: label },
                            })
                        })
                    }
                />
            )}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const TestDataA01 = ({ LabList, title, opgType }) => {
    const BoxCharts = useRef()
    const size = useSize(BoxCharts)
    const [ActiveOne, setActiveOne] = useState()
    const [TabsOne, setTabsOne] = useState([])
    const [OneData, setOneData] = useState([])
    const { runAsync: getOrganizations } = useRequest(Http, { manual: true })
    const { runAsync: getConstructionLabDataStat } = useRequest(Http, { manual: true })

    useEffect(() => {
        getOrganizations({ url: 'getOrganizations', data: { OrgType: opgType } }).then(({ list }) => {
            let data = list.map(({ uuid, tableName }) => ({ label: tableName, value: uuid }))
            setActiveOne(list[0]?.uuid)
            setTabsOne(data)
        })
    }, [getOrganizations, opgType])

    const [ChartsOne, setChartsOne] = useState()

    useEffect(() => {
        if (size) {
            const { width, height } = size
            const configOne = {
                data: OneData,
                color: 'l(90) 0:rgba(176, 254, 246, 1) 1:rgba(176, 254, 246, 0.4)',
                autoFit: false,
                width,
                height,
                maxColumnWidth: 14,
                appendPadding: 16,
                xField: 'type',
                yField: '试验次数',
                xAxis: {
                    label: { style: { fill: '#B2FBFD' } },
                    line: { style: { stroke: '#B2FBFD' } },
                    tickLine: { style: { stroke: '#B2FBFD' } },
                },
                yAxis: {
                    title: { text: '组', position: 'end', autoRotate: false, offset: 55, style: { fill: '#B2FBFD' } },
                    tickCount: 5,
                    label: { style: { fill: '#B2FBFD' }, formatter: e => e },
                    grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
                },
                scrollbar: {
                    type: 'horizontal',
                    height: 8,
                    categorySize: 80,
                    style: {
                        trackColor: 'rgba(178, 251, 253, 0.2)',
                        thumbColor: 'rgba(178, 251, 253, 0.6)',
                        thumbHighlightColor: '#B2FBFD',
                    },
                },
            }
            setChartsOne(configOne)
        }
    }, [OneData, size])

    useEffect(() => {
        if (ActiveOne)
            getConstructionLabDataStat({
                url: 'getConstructionGetlabDataStatByOrg',
                data: {
                    OrganizationUuid: ActiveOne,
                    LabType: LabList,
                },
            }).then(res =>
                setOneData(
                    Object.keys(res).map(item => ({
                        type: TestNameMapping[item].title,
                        试验次数: res[item],
                        uuid: TestNameMapping[item].uuid,
                        OrganizationUuid: ActiveOne,
                    })),
                ),
            )
    }, [ActiveOne, getConstructionLabDataStat, LabList])

    const [OptionsCall, setOptionsCall] = useState()
    const OptionsEvent = useEventEmitter()
    OptionsEvent.useSubscription(val => setOptionsCall(val))

    const ClickCharts = (plot, e) => {
        const { x, y } = e
        const [{ data }] = plot.chart.getTooltipItems({ x, y })
        const { uuid, OrganizationUuid } = data
        const { label, title } = TestTypeMapping[uuid]
        setOptionsCall({
            type: 'TableList',
            data: {
                title,
                type: label,
                uuid: OrganizationUuid,
            },
        })
    }
    return (
        <div className="TestDataA01">
            <div>
                <div className="Tabs">
                    <Select
                        value={ActiveOne}
                        style={{ width: '100%' }}
                        options={TabsOne}
                        suffixIcon={<CaretDownOutlined style={{ color: 'white' }} />}
                        onChange={e => setActiveOne(e)}
                    />
                </div>
                <div className="Charts" ref={BoxCharts}>
                    {ChartsOne && (
                        <Column {...ChartsOne} onReady={plot => plot.on('plot:click', e => ClickCharts(plot, e))} />
                    )}
                </div>
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

const TestTempA01List = [
    {
        uuid: 1,
        title: '弯沉',
        value: '弯沉点数',
        unit: '点',
        img: 'TestTempA01_A01.png',
        type: 'NongKenGetDeflectionList',
    },
    {
        uuid: 2,
        title: '桩基',
        value: '桩基个数',
        unit: '个',
        img: 'TestTempA01_A02.png',
        type: 'NongKenGetPileFoundationList',
    },
]

const TestTempA01Nav = [
    { uuid: 1, title: '本月试验检测统计' },
    { uuid: 2, title: '累计试验检测统计' },
]

export const TestTempA01 = ({ OrgEvent }) => {
    const ChartsA01 = useRef()
    const sizeA01 = useSize(ChartsA01)
    const ChartsA02 = useRef()
    const sizeA02 = useSize(ChartsA02)
    const [Active, setActive] = useState(1)
    const [Org, setOrg] = useState('')
    OrgEvent.useSubscription(val => {
        if (val === '00000000-0000-0000-0000-000000000000') val = ''
        setOrg(val)
        getTop({ url: 'getNongkenGetLabstatisticsInfo', data: { OrganizationUuid: val } })
        getBtm({ url: 'getNongkenGetLabMonthReport', data: { OrganizationUuid: val } })
        getTest({ url: 'getNongkenGetDeflection', data: { OrganizationUuid: val } })
    })

    const A01List = [
        { uuid: 1, label: '未合格数据', value: '不合格占比', unit: '%', color: 'rgba(98, 212, 230, 1)' },
        { uuid: 2, label: '合格数据', value: '合格占比', unit: '%', color: 'rgba(119, 195, 255, 1)' },
    ]

    const [A01Data, setA01Data] = useState({ 总数: 0, 合格占比: 0, 不合格占比: 0 })
    const [A02Data, setA02Data] = useState([])
    const [A03AData, setA03AData] = useState([])
    const [A03BData, setA03BData] = useState([])
    const [A04Data, setA04Data] = useState({ 弯沉点数: 0, 桩基个数: 0 })

    const { runAsync: getTop } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const { labList, statuList } = res
            setA01Data(statuList)
            setA02Data(
                labList.map(({ 名称, 数量, 编号 }) => ({
                    name: '试验总数据',
                    type: TestNameMapping[名称].title,
                    value: 数量,
                    uuid: 编号,
                })),
            )
        },
    })
    const { runAsync: getBtm } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setA03AData(
                res.list.map(({ 类别, 本月试验次数 }) => ({ name: '本月次数', type: 类别, value: 本月试验次数 })),
            )
            setA03BData(
                res.list.map(({ 类别, 累计试验次数 }) => ({ name: '累计次数', type: 类别, value: 累计试验次数 })),
            )
        },
    })
    const { runAsync: getTest } = useRequest(Http, { manual: true, onSuccess: res => setA04Data(res) })

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className="TestTempA01">
            <div className="Top">
                <div className="left">
                    <TitleSmall001 title="数据合格率" />
                    <div className="box">
                        <div>
                            <div>试验数据总数</div>
                            <div>
                                {A01Data.总数} <span>万条</span>
                            </div>
                        </div>
                        <div>
                            <PieTemplate
                                size={124}
                                data={[
                                    { type: '合格数据', value: Number(A01Data.合格占比) },
                                    { type: '未合格数据', value: Number(A01Data.不合格占比) },
                                ]}
                                color={['rgba(18, 199, 154, 1)', 'rgba(199, 82, 18, 1)']}
                            />
                            <div>
                                {A01List.map(({ uuid, label, value, unit, color }) => (
                                    <div key={uuid}>
                                        <div style={{ color }}>{label}</div>
                                        <div>
                                            {A01Data[value]}
                                            {unit}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
                <div className="right">
                    <TitleSmall001 title="试验数据" />
                    <div className="box" ref={ChartsA01}>
                        {sizeA01 && (
                            <ColumnConfigA01Template
                                data={A02Data}
                                size={sizeA01}
                                style={ColumnStyle}
                                click={e => {
                                    setOptionsCall({
                                        type: 'TableList',
                                        data: {
                                            title: e.type + '试验数据',
                                            type: e.uuid,
                                            uuid: Org,
                                        },
                                    })
                                }}
                            />
                        )}
                    </div>
                </div>
            </div>
            <div className="Btm">
                <div className="left">
                    <TitleSmall001 title="试验检测月报" />
                    <div
                        className="box"
                        onClick={() => {
                            setOptionsCall({
                                type: 'OpenExcel',
                                data: {
                                    title: '月报信息',
                                    width: 1500,
                                    data: {
                                        save: true,
                                        OrganizationUuid: Org,
                                        url: 'getNongkenGetLabMonthReportExcelByOrg',
                                    },
                                },
                            })
                        }}
                    >
                        <div className="nav">
                            {TestTempA01Nav.map(({ uuid, title }) => (
                                <div
                                    key={uuid}
                                    className={uuid === Active ? 'active' : ''}
                                    onClick={() => setActive(uuid)}
                                >
                                    {title}
                                </div>
                            ))}
                        </div>
                        <div className="Charts" ref={ChartsA02}>
                            {sizeA02 && (
                                <ColumnConfigA01Template
                                    data={Active === 1 ? A03AData : A03BData}
                                    size={sizeA02}
                                    style={ColumnStyle}
                                />
                            )}
                        </div>
                    </div>
                </div>
                <div className="right">
                    <TitleSmall001 title="关键指标检测" />
                    <div className="box">
                        {TestTempA01List.map(({ uuid, title, value, unit, img, type }) => (
                            <div
                                className="list"
                                key={uuid}
                                onClick={() => {
                                    setOptionsCall({
                                        type: 'TableList',
                                        data: { type, title: `${title}试验详情`, OrganizationUuid: Org },
                                    })
                                }}
                            >
                                <div>
                                    <img src={WebCommonUrl + 'MaterialTransportationA01_BTM.png'} alt="" />
                                    <img src={WebCommonUrl + img} alt="" />
                                </div>
                                <div>
                                    <div>{title}数量</div>
                                    <div>
                                        <div>
                                            {A04Data[value]}
                                            <img src={WebCommonUrl + 'MaterialTransportationA01_Num.png'} alt="" />
                                        </div>
                                        <div>{unit}</div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}
